import { useState } from 'react';
import { 
  Card, Button, Input, Select, DatePicker, 
  Typography, Avatar, Tag, Space, 
  Table, Popconfirm, message, Divider 
} from 'antd';
import { 
  PlusOutlined, DeleteOutlined, SaveOutlined, 
  CalendarOutlined, UserOutlined, 
  CheckCircleOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import './arrange.css';

// 模拟员工数据
const doctorsData = [
  { id: 1, name: '李员工', specialty: '推拿按摩', color: '#1890ff' },
  { id: 2, name: '陈员工', specialty: '针灸治疗', color: '#f50' },
  { id: 3, name: '赵员工', specialty: '艾灸养生', color: '#52c41a' },
  { id: 4, name: '王员工', specialty: '拔罐疗法', color: '#faad14' },
  { id: 5, name: '张员工', specialty: '针灸治疗', color: '#f50' },
  { id: 6, name: '刘员工', specialty: '推拿按摩', color: '#1890ff' },
];

// 班次选项
const shiftOptions = [
  { value: 'morning', label: '早班 (09:00-12:00)' },
  { value: 'afternoon', label: '中班 (14:00-17:00)' },
  { value: 'evening', label: '晚班 (18:00-21:00)' }
];

export const AddArrange = () => {
  // 状态管理
  const [selectedDate, setSelectedDate] = useState(dayjs());
  const [selectedShift, setSelectedShift] = useState('morning');
  const [selectedDoctor, setSelectedDoctor] = useState(null);
  const [arrangedDoctors, setArrangedDoctors] = useState([]);
  const [capacity, setCapacity] = useState(3);
  const [notes, setNotes] = useState('');

  // 表格列定义
  const columns = [
    {
      title: '员工信息',
      dataIndex: 'doctor',
      key: 'doctor',
      render: (doctor) => (
        <Space align="center">
          <Avatar style={{ backgroundColor: doctor.color }}>
            {doctor.name.charAt(0)}
          </Avatar>
          <div>
            <div>{doctor.name}</div>
            <Tag color={doctor.color} size="small">{doctor.specialty}</Tag>
          </div>
        </Space>
      ),
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Popconfirm
          title="确定要移除这位员工吗？"
          onConfirm={() => handleRemoveDoctor(record.key)}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            icon={<DeleteOutlined />} 
            size="small" 
            danger 
            className="hover:bg-red-600 transition-colors"
          />
        </Popconfirm>
      ),
    },
  ];

  // 处理添加员工
  const handleAddDoctor = () => {
    if (!selectedDoctor) {
      message.warning('请先选择一位员工');
      return;
    }

    // 检查是否已添加该员工
    const alreadyAdded = arrangedDoctors.some(
      item => item.doctor.id === selectedDoctor.id
    );
    
    if (alreadyAdded) {
      message.warning('这位员工已在排班列表中');
      return;
    }

    // 添加新员工到排班
    const newDoctor = {
      key: Date.now(), // 使用时间戳作为唯一key
      doctor: selectedDoctor,
      capacity: capacity
    };

    setArrangedDoctors([...arrangedDoctors, newDoctor]);
    setSelectedDoctor(null);
    setCapacity(3); // 重置默认容量
  };

  // 处理移除员工
  const handleRemoveDoctor = (key) => {
    setArrangedDoctors(arrangedDoctors.filter(item => item.key !== key));
    message.success('已移除该员工');
  };


  // 处理保存排班
  const handleSaveArrange = () => {
    if (arrangedDoctors.length === 0) {
      message.warning('请至少添加一位员工');
      return;
    }

    // 构建排班数据
    const arrangeData = {
      date: selectedDate.format('YYYY-MM-DD'),
      shift: selectedShift,
      doctors: arrangedDoctors,
      notes: notes,
      createdAt: new Date().toISOString()
    };

    // 这里可以添加API调用保存数据
    console.log('保存排班数据:', arrangeData);
    
    // 显示成功消息
    message.success({
      content: '排班保存成功',
      icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
    });
    
    // 重置表单
    resetForm();
  };

  // 重置表单
  const resetForm = () => {
    setSelectedDate(dayjs());
    setSelectedShift('morning');
    setSelectedDoctor(null);
    setArrangedDoctors([]);
    setCapacity(3);
    setNotes('');
  };

  return (
    <div className="modal-box" style={{height:"520px"}}>
      <Typography.Title level={2} className="page-title">
        <CalendarOutlined className="title-icon" /> 新增排班
      </Typography.Title>
      
      <Card className="arrange-card" style={{marginTop:10}}>
        <div className="form-section">
          <Typography.Title level={4} className="section-title">
            <UserOutlined className="section-icon" /> 排班基本信息
          </Typography.Title>
          
          <div className="form-row">
            <div className="form-item">
              <Typography.Text strong>排班日期</Typography.Text>
              <DatePicker
                value={selectedDate}
                onChange={(date) => setSelectedDate(date)}
                style={{ width: '100%' }}
                placeholder="选择日期"
                className="form-control"
              />
            </div>
            
            <div className="form-item">
              <Typography.Text strong>班次</Typography.Text>
              <Select
                value={selectedShift}
                onChange={(value) => setSelectedShift(value)}
                style={{ width: '100%' }}
                placeholder="选择班次"
                className="form-control"
              >
                {shiftOptions.map(option => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </div>
          </div>
          
          <div className="form-item full-width">
            <Typography.Text strong>备注信息（可选）</Typography.Text>
            <Input.TextArea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={3}
              placeholder="请输入备注信息，如特殊排班要求等"
              className="form-control"
            />
          </div>
        </div>
        
        <Divider className="section-divider" />
        
        <div className="form-section">
          <Typography.Title level={4} className="section-title">
            <UserOutlined className="section-icon" /> 排班员工
          </Typography.Title>
          
          <div className="add-doctor-section">
            <div className="form-row">
              <div className="form-item">
                <Typography.Text strong>选择员工</Typography.Text>
                <Select
                  value={selectedDoctor?.id}
                  onChange={(value) => {
                    const doctor = doctorsData.find(d => d.id === value);
                    setSelectedDoctor(doctor);
                  }}
                  style={{ width: '100%' }}
                  placeholder="选择要排班的员工"
                  showSearch
                  filterOption={(input, option) => 
                    (option?.children ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                  className="form-control"
                >
                  {doctorsData.map(doctor => (
                    <Select.Option key={doctor.id} value={doctor.id}>
                      <div className="select-option-content">
                        <div 
                          className="specialty-indicator" 
                          style={{ backgroundColor: doctor.color }}
                        ></div>
                        {doctor.name} - {doctor.specialty}
                      </div>
                    </Select.Option>
                  ))}
                </Select>
              </div>
              
            
             
             <div className="form-item">
                <Typography.Text strong>操作</Typography.Text>
                  <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleAddDoctor}
                  className="add-button"
                 
                >
                  添加
                </Button>
              </div>
            </div>
          </div>
          
          <div className="doctors-list">
            {arrangedDoctors.length > 0 ? (
              <Table
                columns={columns}
                dataSource={arrangedDoctors}
                pagination={false}
                rowClassName="doctor-row"
                locale={{ emptyText: '暂无排班员工' }}
              />
            ) : (
              <div className="empty-state">
                <ExclamationCircleOutlined className="empty-icon" />
                <Typography.Text>尚未添加排班员工</Typography.Text>
                <Typography.Text type="secondary" className="empty-hint">
                  请从上方选择员工添加到排班列表
                </Typography.Text>
              </div>
            )}
          </div>
        </div>
        
        <div className="form-actions">
          <Button 
            onClick={resetForm}
            className="reset-button"
          >
            重置
          </Button>
          <Button 
            type="primary" 
            icon={<SaveOutlined />} 
            onClick={handleSaveArrange}
            className="save-button"
            disabled={arrangedDoctors.length === 0}
          >
            保存排班
          </Button>
        </div>
      </Card>
    </div>
  );
};
